package com.bbx.taxi.client.Activity.Menu;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;
import butterknife.InjectView;

import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.gclient.GMsg;
import com.bbx.api.sdk.model.official.passanger.Offciail_DelBuild;
import com.bbx.api.sdk.model.official.passanger.Official_OrderListBuild;
import com.bbx.api.sdk.model.official.passanger.Return.OrderList.OfficialOrderList;
import com.bbx.api.sdk.model.official.passanger.Return.OrderList.OfficialOrders;
import com.bbx.api.sdk.model.passanger.MyOrder;
import com.bbx.api.sdk.model.passanger.Order;
import com.bbx.api.sdk.model.passanger.Token;
import com.bbx.api.sdk.model.passanger.Return.Jmsg.Msgs;
import com.bbx.api.sdk.net.base.JsonBuild;
import com.bbx.api.sdk.net.official.passanger.Offciail_OrderDelNet;
import com.bbx.api.sdk.net.official.passanger.Officail_OrderListNet;
import com.bbx.api.sdk.net.passeger.conn.CodeNet;
import com.bbx.api.sdk.net.passeger.conn.LoginNet;
import com.bbx.api.sdk.net.passeger.conn.MyOrderNet;
import com.bbx.api.sdk.net.passeger.conn.MyOrderNet_Unfini;
import com.bbx.api.sdk.net.passeger.conn.OrderDeleteNet;
import com.bbx.taxi.client.Task.BaseAsyncTask;
import com.bbx.taxi.client.Task.MyOrderTask;
import com.bbx.taxi.client.Task.MyUnprocessedTask;
import com.bbx.api.util.SharedPreEncryptUtil;
import com.bbx.taxi.client.MyApplication;
import com.bbx.taxi.official.R;
import com.bbx.taxi.client.Activity.MainActivity;
import com.bbx.taxi.client.Activity.Address.AddressActivity;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.Activity.Guide.ViewPagerScroller;
import com.bbx.taxi.client.Activity.Order.OrderCancelReason;
import com.bbx.taxi.client.Activity.Order.OrderEvaluationActivity;
import com.bbx.taxi.client.Activity.Order.OrderEvaluationActivity2;
import com.bbx.taxi.client.Activity.Order.OrderUnprocessed;
import com.bbx.taxi.client.Activity.Order.StartServiceActivity;
import com.bbx.taxi.client.Activity.login.LoginActivity;
import com.bbx.taxi.client.Activity.login.LoginActivity.CodeTask;
import com.bbx.taxi.client.Adapter.AddressAdapter;
import com.bbx.taxi.client.Adapter.EditAddressAdapter;
import com.bbx.taxi.client.Adapter.MyOrderAdapter;
import com.bbx.taxi.client.Adapter.OrderTypeAdapter;
import com.bbx.taxi.client.Adapter.OrderTypeAdapter.ViewOrderTypeHolder;
import com.bbx.taxi.client.Adapter.Page.MyPagerAdapter;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.Bean.Extra.ExamineMsg;
import com.bbx.taxi.client.Bean.Extra.MainMsg;
import com.bbx.taxi.client.Bean.Extra.OrderMsg;
import com.bbx.taxi.client.DB.CouponDB;
import com.bbx.taxi.client.DB.MyOrder.MyOrderDB;
import com.bbx.taxi.client.DB.MyOrder.MyOrderLocationsDB;
import com.bbx.taxi.client.DB.MyOrder.MyOrderingDB;
import com.bbx.taxi.client.DB.Util.DBcolumns;
import com.bbx.taxi.client.Service.LoginService;
import com.bbx.taxi.client.Util.ClickFilter;
import com.bbx.taxi.client.Util.DataCleanManager;
import com.bbx.taxi.client.Util.DateFormat;
import com.bbx.taxi.client.Util.FormatUtil;
import com.bbx.taxi.client.Util.ToCity;
import com.bbx.taxi.client.widget.MyViewPager;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog;
import com.bbx.taxi.client.widget.Dailog.MyBusyDailog;
import com.bbx.taxi.client.widget.Dailog.MyPayOrderDailog;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog.onClickLeftListener;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog.onClickRightListener;
import com.bbx.taxi.client.widget.Dailog.MyPayOrderDailog.onClickPayListener;
import com.bbx.taxi.client.widget.DropDown.DropDownMenu;
import com.bbx.taxi.client.widget.DropDown.DropDownMenu.OnShowStatusListener;
import com.bbx.taxi.client.widget.DropDown.GirdDropDownAdapter;
import com.bbx.taxi.client.widget.DropDown.ListDropDownAdapter;
import com.bbx.taxi.client.widget.StatusBar.StatusBar;
import com.example.Util.DensityUtil;
import com.example.loadview.LoadingDialog;
import com.example.mylistview.pullListView.PullToRefreshLayout;
import com.example.mylistview.pullListView.PullToRefreshLayout.OnRefreshListener;
import com.example.mylistview.pullListView.PullableListView;
import com.example.mylistview.pullListView.PullableListView.OnLoadListener;
import com.example.mylistview.swipemenu.MyListView;
import com.example.mylistview.swipemenu.MyListView.OnMenuItemClickListener;
import com.example.mylistview.swipemenu.MyListView.OnSwipeListener;
import com.example.mylistview.swipemenu.SwipeMenu;
import com.example.mylistview.swipemenu.SwipeMenuCreator;
import com.example.mylistview.swipemenu.SwipeMenuItem;
import com.example.mylistview.swipemenu.SwipeMenuLayout;
import com.example.mylistview.swipemenu.SwipeMenuLayout.OnMenuSwitchStateListener;

/**
 * @Path com.bbx.taxi.client.Activity.Menu.MyOrderOfficailActivity.java
 * @Author 严旭文
 * @Date 2016-1-14 下午3:02:03
 * @Company 蓝海（福建）信息技术有限公司
 * @Description
 */
public class MyOrderOfficailActivity extends BaseBBXActivity implements OnPageChangeListener{
	private MyListView mMyListView_AllOrder;
	private PullToRefreshLayout pullToRefreshLayout_all;
	private LinearLayout layout_nodata_all;
	ArrayList<OfficialOrderList> list_all = new ArrayList<OfficialOrderList>();
	private MyOrderAdapter mMyOrderAdapter_allOrder;
	private int bmp_width = 0;// 图片大小
	private int bmp_height = 0;// 图片大小
	private String start_id = "0";
	private MyOrderDB db_myorder;// 我的订单数据库
	private MyOrderingDB db_myordering;// 我的进行中的订单数据库
	private MyOrderLocationsDB db_locations;// 我的订单的Locations数据库
	@InjectView(R.id.dropDownMenu)
	DropDownMenu mDropDownMenu;
	/** 加载跟刷新的数量 */
	public static int num_ing = 100;
	/** 加载跟刷新的数量 */
	public static int num_all = 10;
	/** 加载跟刷新的数量 */
	public static int num_all2 = 100;
	/** 进行中的订单当前最后一项的Id */
	private int last_id_ordering;
	private Handler handler = new Handler();
	private MyOrderTask mMyOrderTask;
	private DeleteOrderTask mDeleteOrderTask;
	private boolean isFirst_ing = true;
	private boolean isFirst_all = true;
	private int flag = Value.TYPE_ALL;
	private int own_expense = Value.OWNALL;
	private MyViewPager mViewPager;
	private MyPagerAdapter mMyPagerAdapter;
	private TextView tv_all,tv_gongwu,tv_putong;
	private ImageView image_bar;
	private int viewpageId = 0;
	private int oldviewpageId = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_menu_myorder_officail);
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void onResume() {
		isRefreshOrder = false;
		super.onResume();
	}

	@Override
	protected void initView() {
		setTitle(true, getString(R.string.title_order),
				R.drawable.btn_top_order_s, "");
		db_myorder = new MyOrderDB(this);
		db_myordering = new MyOrderingDB(this);
		db_locations = new MyOrderLocationsDB(this);
		initDropDown();
		initMyListView();
		mMyOrderAdapter_allOrder = new MyOrderAdapter(this, list_all);
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View headerview = inflater.inflate(R.layout.headerview, null);
		// 【主要，添加headerview，则在OnItenClick中的Position就会错乱】
		mMyListView_AllOrder.setAdapter(mMyOrderAdapter_allOrder);
		initswipe2();
		onReadDB(true);
	}

	@Override
	protected void initData() {
	}

	public void initDropDown() {
		ArrayList<View> popupViews = new ArrayList<View>();
//		//全部
		final ListView alltypeView = new ListView(this);
		alltypeView.setVerticalScrollBarEnabled(true);
		ArrayList<String> listType = new ArrayList<String>();
		listType.add(getString(R.string.all_order));
		listType.add(getString(R.string.unprocessed_order));
		listType.add(getString(R.string.refused_order));
		listType.add(getString(R.string.ordering));
		listType.add(getString(R.string.finish_order));
		listType.add(getString(R.string.cancel_order));
		final GirdDropDownAdapter mAllGirdDropDownAdapter = new GirdDropDownAdapter(this, listType);
		alltypeView.setDividerHeight(0);
		alltypeView.setAdapter(mAllGirdDropDownAdapter);
//		//公务
		final ListView gongwutypeView = new ListView(this);
		gongwutypeView.setVerticalScrollBarEnabled(true);
		ArrayList<String> gongwulistType = new ArrayList<String>();
		gongwulistType.add(getString(R.string.all_order));
		gongwulistType.add(getString(R.string.unprocessed_order));
		gongwulistType.add(getString(R.string.refused_order));
		gongwulistType.add(getString(R.string.ordering));
		gongwulistType.add(getString(R.string.finish_order));
		gongwulistType.add(getString(R.string.cancel_order));
		final GirdDropDownAdapter mgongwuGirdDropDownAdapter = new GirdDropDownAdapter(this, gongwulistType);
		mgongwuGirdDropDownAdapter.setCheckItem(-1);
		gongwutypeView.setDividerHeight(0);
		gongwutypeView.setAdapter(mgongwuGirdDropDownAdapter);
		//普通
		final ListView putongtypeView = new ListView(this);
		putongtypeView.setVerticalScrollBarEnabled(true);
		ArrayList<String> putonglistType = new ArrayList<String>();
		putonglistType.add(getString(R.string.all_order));
		putonglistType.add(getString(R.string.ordering));
		putonglistType.add(getString(R.string.finish_order));
		putonglistType.add(getString(R.string.cancel_order));
		final GirdDropDownAdapter mputongGirdDropDownAdapter = new GirdDropDownAdapter(this, putonglistType);
		mputongGirdDropDownAdapter.setCheckItem(-1);
		putongtypeView.setDividerHeight(0);
		putongtypeView.setAdapter(mputongGirdDropDownAdapter);
		popupViews.add(alltypeView);
		popupViews.add(gongwutypeView);
		popupViews.add(putongtypeView);
		
		View drawdowntitle = LayoutInflater.from(context).inflate(
				R.layout.drawdowntitle, null);
		drawdowntitle.setLayoutParams(new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.WRAP_CONTENT));
		 mViewPager=(MyViewPager)drawdowntitle.findViewById(R.id.viewpager);
		 ViewPagerScroller scroller = new ViewPagerScroller(this);
		 scroller.setScrollDuration(800);
		 scroller.initViewPagerScroll(mViewPager);//这个是设置切换过渡时间为0.8秒
		 tv_all=(TextView)drawdowntitle.findViewById(R.id.tv_all);
		 tv_gongwu=(TextView)drawdowntitle.findViewById(R.id.tv_gongwu);
		 tv_putong=(TextView)drawdowntitle.findViewById(R.id.tv_putong);
		 image_bar=(ImageView)drawdowntitle.findViewById(R.id.image_bar);
		 initBar();
		tv_all.setOnClickListener(this);
		tv_gongwu.setOnClickListener(this);
		tv_putong.setOnClickListener(this);
		mMyPagerAdapter=new MyPagerAdapter(popupViews);
		mViewPager.setAdapter(mMyPagerAdapter);// 绑定数据
		mViewPager.setCurrentItem(0);// 设置默认子试图
		mViewPager.setOnPageChangeListener(this);
		
		
		alltypeView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				mAllGirdDropDownAdapter.setCheckItem(position);
				mgongwuGirdDropDownAdapter.setCheckItem(-1);
				mputongGirdDropDownAdapter.setCheckItem(-1);
				own_expense=Value.OWNALL;
				switch (position) {
				case 0:
					flag = Value.TYPE_ALL;
					break;
				case 1:
					flag = Value.TYPE_UNP;
					break;
				case 2:
					flag = Value.TYPE_REFUSE;
					break;
				case 3:
					flag = Value.TYPE_ING;
					break;
				case 4:
					flag = Value.TYPE_FINISH;
					break;
				case 5:
					flag = Value.TYPE_CANCEL;
					break;
				}
				mDropDownMenu.closeMenu();
				context.layout.setOnClose(false);
				refreshAllOrder(false);
			}
		});
		gongwutypeView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				mAllGirdDropDownAdapter.setCheckItem(-1);
				mgongwuGirdDropDownAdapter.setCheckItem(position);
				mputongGirdDropDownAdapter.setCheckItem(-1);
				own_expense=Value.NOOWN;
				switch (position) {
				case 0:
					flag = Value.TYPE_ALL;
					break;
				case 1:
					flag = Value.TYPE_UNP;
					break;
				case 2:
					flag = Value.TYPE_REFUSE;
					break;
				case 3:
					flag = Value.TYPE_ING;
					break;
				case 4:
					flag = Value.TYPE_FINISH;
					break;
				case 5:
					flag = Value.TYPE_CANCEL;
					break;
				}
				mDropDownMenu.closeMenu();
				context.layout.setOnClose(false);
				refreshAllOrder(false);	
			}
		});
		putongtypeView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				mAllGirdDropDownAdapter.setCheckItem(-1);
				mgongwuGirdDropDownAdapter.setCheckItem(-1);
				mputongGirdDropDownAdapter.setCheckItem(position);
				own_expense=Value.OWN;
				switch (position) {
				case 0:
					flag = Value.TYPE_ALL;
					break;
				case 1:
					flag = Value.TYPE_ING;
					break;
				case 2:
					flag = Value.TYPE_FINISH;
					break;
				case 3:
					flag = Value.TYPE_CANCEL;
					break;
				}
				mDropDownMenu.closeMenu();
				context.layout.setOnClose(false);
				refreshAllOrder(false);	
			}
		});
		// init context view
		View contentView = LayoutInflater.from(context).inflate(
				R.layout.activity_myorder_content, null);
		contentView.setLayoutParams(new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT));
		String headers[] = {""};
		ArrayList<View> Views = new ArrayList<View>();
		Views.add(drawdowntitle);
		mDropDownMenu.setDropDownMenu(Arrays.asList(headers), Views,
				contentView);
		mDropDownMenu.setmOnShowStatusListener(new OnShowStatusListener() {
			@Override
			public void onShowStatus(boolean isShow) {
				if(isShow){
					context.layout.setOnClose(true);
				}else{
					context.layout.setOnClose(false);
				}
				
			}
		});
		mMyListView_AllOrder = (MyListView) contentView
				.findViewById(R.id.MyListView);
		pullToRefreshLayout_all = (PullToRefreshLayout) contentView
				.findViewById(R.id.pullToRefreshLayout);
		layout_nodata_all = (LinearLayout) contentView
				.findViewById(R.id.layout_nodata);
	}
	public void initBar(){
		bmp_width = BitmapFactory
				.decodeResource(getResources(), R.drawable.bar).getWidth();// 获取图片宽度
		bmp_height = BitmapFactory.decodeResource(getResources(),
				R.drawable.bar).getHeight();// 获取图片高度度
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenW = dm.widthPixels;// 获取分辨率宽度
		LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) image_bar
				.getLayoutParams(); // 取控件textView当前的布局参数
		linearParams.height = bmp_height;

		linearParams.width = (screenW / 3);
		image_bar.setLayoutParams(linearParams);
	}

	@Override
	protected void desotryItems() {

	}

	private void initMyListView() {
		pullToRefreshLayout_all.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
				refreshAllOrder(true);
			}
		});

		mMyListView_AllOrder.setOnLoadListener(new OnLoadListener() {

			@Override
			public void onLoad(PullableListView pullableListView) {
				loadMoreAllOrder(true);
			}
		});

		mMyListView_AllOrder.setEmptyView(layout_nodata_all);
		mMyListView_AllOrder.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (!ClickFilter.filter(1000L))
					return;
				// TODO【 修正有Header的ListView的position的BUG 】
				int headerViewsCount = mMyListView_AllOrder
						.getHeaderViewsCount();// 得到header的总数量
				// 【得到新的修正后的position】
				int newPosition = position - headerViewsCount;
				String audit_status=list_all.get(newPosition).getAudit_status();
				   int status=Integer.parseInt(list_all.get(newPosition).getOrder_status());
				if(status==Value.ORDER_STATUS_UNTREATED&&audit_status!=null&&audit_status.equals(Value.STATUS_AUDIT_NO)){
					OrderUnprocessed.setOrder(list_all.get(newPosition),list_all.get(newPosition).getOrder_id());
					context.startActivityForResult(new Intent(context,OrderUnprocessed.class)
					.putExtra(ExamineMsg.EXAMINE_TYPE,ExamineMsg.TYPE_OF)
					.putExtra(ExamineMsg.EXAMINE_STATUS,ExamineMsg.STATUS_NO),requestCode);
				}else if(status==Value.ORDER_STATUS_UNTREATED&&audit_status!=null&&audit_status.equals(Value.STATUS_AUDIT_NOPASS)){
					OrderUnprocessed.setOrder(list_all.get(newPosition),list_all.get(newPosition).getOrder_id());
					context.startActivityForResult(new Intent(context,OrderUnprocessed.class)
					.putExtra(ExamineMsg.EXAMINE_TYPE,ExamineMsg.TYPE_OF)
					.putExtra(ExamineMsg.EXAMINE_STATUS,ExamineMsg.STATUS_AGAIN),requestCode);
				}else{
				if ( status< Value.ORDER_STATUS_OFFCAR
						|| status == Value.ORDER_STATUS_GAIPAI
						||status == Value.ORDER_STATUS_KF_GAIPAI) {
					Intent intent = new Intent(context,
							StartServiceActivity.class);
					intent.putExtra(OrderMsg.extra_type,OrderMsg.TYPE_LIST);
					intent.putExtra(OrderMsg.extra_order_id,
							list_all.get(newPosition).getOrder_id());
					startActivityForResult(intent, requestCode);
				} else if (status == Value.ORDER_STATUS_FINISH
						|| status == Value.ORDER_STATUS_OFFCAR) {
					Intent intent = new Intent(context,
							OrderEvaluationActivity2.class);
					intent.putExtra(OrderMsg.order_id_finish,
							list_all.get(newPosition).order_id);
					intent.putExtra(OrderMsg.finish_type, OrderMsg.finish_all);
					startActivityForResult(intent, requestCode);
				} else if (status == Value.ORDER_STATUS_CANCEL
						|| status == Value.ORDER_STATUS_KF_CANCEL) {
					Intent intent = new Intent(context, OrderCancelReason.class);
					intent.putExtra(OrderMsg.extra_order_id,
							list_all.get(newPosition).order_id);
					startActivityForResult(intent, requestCode);

				} else {
					Intent intent = new Intent(context,
							OrderEvaluationActivity2.class);
					intent.putExtra(OrderMsg.order_id_finish,
							list_all.get(newPosition).order_id);
					startActivityForResult(intent, requestCode);
				}
			  }
			}
		});

	}

	/**
	 * 初始化ListView的Item菜单
	 */
	private void initswipe2() {

		// step 1. create a MenuCreator
		SwipeMenuCreator creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				// create "open" item
				SwipeMenuItem openItem = new SwipeMenuItem(
						getApplicationContext());
				// set item background
				openItem.setBackgroundColor(getResources()
						.getColor(R.color.light_blue));
				// set item width
				openItem.setWidth(DensityUtil.dip2px(context, 65));
				openItem.setIcon(R.drawable.icon_delete);
				// set item title
//				openItem.setTitle(getString(R.string.delete));
				// set item title fontsize
				openItem.setTitleSize(18);
				// set item title font color
				openItem.setTitleColor(Color.WHITE);
				// add to menu
				menu.addMenuItem(openItem);

				// // create "delete" item
				// SwipeMenuItem deleteItem = new SwipeMenuItem(
				// getApplicationContext());
				// // set item background
				// deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
				// 0x3F, 0x25)));
				// // set item width
				// deleteItem.setWidth(dp2px(90));
				// // set a icon
				// deleteItem.setIcon(R.drawable.ic_delete);
				// // add to menu
				// menu.addMenuItem(deleteItem);
			}
		};
		// set creator
		// mMyListView_Ordering.setMenuCreator(creator);
		mMyListView_AllOrder.setMenuCreator(creator);

		// step 2. listener item click event
		// mMyListView_Ordering
		// .setOnMenuItemClickListener(new OnMenuItemClickListener() {
		// @Override
		// public void onMenuItemClick(int position, SwipeMenu menu,
		// int index) {
		// // ApplicationInfo item = mAppList.get(position);
		// switch (index) {
		// case 0:
		// break;
		//
		// }
		// }
		// });
		mMyListView_AllOrder
				.setOnMenuItemClickListener(new OnMenuItemClickListener() {
					@Override
					public void onMenuItemClick(final int position,
							SwipeMenu menu, int index) {
						// ApplicationInfo item = mAppList.get(position);
						switch (index) {
						case 0:
							final MyAlertDailog dialog = new MyAlertDailog(
									context);
							Resources res = context.getResources();
							dialog.setTitle(res
									.getString(R.string.mydailog_title));
							dialog.setContent(res
									.getString(R.string.mydailog_content_delete));
							dialog.setLeftButtonText(res
									.getString(R.string.mydailog_close));
							dialog.setRightButtonText(res
									.getString(R.string.mydailog_delete));
							if (dialog != null && !dialog.isShowing()) {
								dialog.show();
							}
							dialog.setOnClickLeftListener(new onClickLeftListener() {
								@Override
								public void onClickLeft() {
									dialog.dismiss();
								}
							});
							dialog.setOnClickRightListener(new onClickRightListener() {

								@Override
								public void onClickRight() {
									dialog.dismiss();
									boolean isDel=false;
									String audit_status=list_all.get(position).getAudit_status();
									int status=Integer.parseInt(list_all.get(position).getOrder_status());
									//未审核不能删除
									if(status==Value.ORDER_STATUS_UNTREATED&&audit_status!=null&&audit_status.equals(Value.STATUS_AUDIT_NO)){
										isDel=false;
									}else{
										isDel=true;
									}
									if (( (audit_status!=null&&!audit_status.equals(Value.STATUS_AUDIT_NOPASS))&&
											status<= Value.ORDER_STATUS_OFFCAR
											&& status != Value.ORDER_STATUS_GAIPAI
											&& status != Value.ORDER_STATUS_KF_GAIPAI)||isDel==false) {
										ToastUtil.showToast(context,
												R.string.ordering_no_delete);
										handler.postDelayed(new Runnable() {
											@Override
											public void run() {
												mMyListView_AllOrder
														.closeMenu();
											}
										}, 200);
									} else {
										Offciail_DelBuild mOffciail_DelBuild = new Offciail_DelBuild(context);
										mOffciail_DelBuild.passenger_id = mApplication.getUid();
										mOffciail_DelBuild.order_id = list_all
												.get(position).order_id;
										mDeleteOrderTask = new DeleteOrderTask(
												context, mOffciail_DelBuild, position);
										mDeleteOrderTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
									}
								}
							});
							break;

						}
					}
				});
		// set SwipeListener
		// mMyListView_Ordering.setOnSwipeListener(new OnSwipeListener() {
		//
		// @Override
		// public void onSwipeStart(int position) {
		// // swipe start
		// }
		//
		// @Override
		// public void onSwipeEnd(int position) {
		// }
		// });
		mMyListView_AllOrder.setOnSwipeListener(new OnSwipeListener() {

			@Override
			public void onSwipeStart(int position) {
				pullToRefreshLayout_all.setIsProhibitPull(true);
			}

			@Override
			public void onSwipeEnd(int position) {
				pullToRefreshLayout_all.setIsProhibitPull(false);
			}
		});
	}
	/**
	 * 刷新全部的订单，isPull判断是否下啦刷新还是，自动刷新
	 */
	public void refreshAllOrder(boolean isPull) {
		start_id=MyOrderTask.TYPE_REFRESH;
		if (loaddialog != null && !loaddialog.isShowing()) {
			loaddialog.show();
		}
		int num=num_all;
		if(flag==Value.TYPE_ING){
			num=num_ing;
		}
		MyOrderTask.getInstance(context, num, flag,own_expense,start_id)
				.setOnOrderFinishListener(this);
	}

	private void loadMoreAllOrder(boolean isAll) {
		start_id = list_all.size()+"";
		MyOrderTask.getInstance(context, num_all, flag,own_expense,start_id)
		.setOnOrderFinishListener(this);
	};

	public class DeleteOrderTask extends BaseAsyncTask {

		private Offciail_DelBuild mOffciail_DelBuild;

		private int delete_id;

		public DeleteOrderTask(Activity context, Offciail_DelBuild mOffciail_DelBuild, int delete_id) {
			super(context);
			this.mOffciail_DelBuild = mOffciail_DelBuild;
			this.delete_id = delete_id;
		}

		@Override
		protected Object doInBackground(Object... params) {
			// TODO Auto-generated method stub
			String json = new JsonBuild().setModel(mOffciail_DelBuild).getJson();
			return new Offciail_OrderDelNet(context, json);
		}

		@Override
		public void onSuccess(Object object) {
			ToastUtil.showToast(context, getString(R.string.del_success));
			db_myorder.onDelete(context,mOffciail_DelBuild.order_id);
			list_all.remove(delete_id);
			notifyDataSetChanged(mMyListView_AllOrder, mMyOrderAdapter_allOrder);

			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					mMyListView_AllOrder.closeMenu();
				}
			}, 200);
		}

		@Override
		public void onFailed(int status, String msg) {
			// TODO Auto-generated method stub
			ToastUtil.showToast(context, getString(R.string.del_fail));
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					mMyListView_AllOrder.closeMenu();
				}
			}, 200);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_right_sub:
			// popview.showAsDropDown(v);
			// pop_background.setVisibility(View.VISIBLE);
			// AlphaAnimation animation = new AlphaAnimation(0f, 1f);
			// animation.setDuration(100);
			// LayoutAnimationController controller = new
			// LayoutAnimationController(animation, 1f);
			// controller.setOrder(LayoutAnimationController.ORDER_NORMAL);
			// listViewType.setLayoutAnimation(controller);
			// mOrderTypeAdapter.notifyDataSetChanged();
			mDropDownMenu.openMenu();
			break;
		case R.id.tv_all:
			mViewPager.setCurrentItem(0);
			break;
		case R.id.tv_gongwu:
			mViewPager.setCurrentItem(1);
			break;
		case R.id.tv_putong:
			mViewPager.setCurrentItem(2);
			break;
		default:
			super.onClick(v);
			break;
		}
	}

	/**
	 * 读取全部订单数据库数据,根据类型，isLoad=true则出现加载框
	 */
	private void onReadDB(final boolean isLoad) {
		new AsyncTask<Void, Void, Void>() {
			protected void onPreExecute() {
				if (loaddialog != null && !loaddialog.isShowing() && isLoad) {
					loaddialog.show();
				}
				super.onPreExecute();
			}

			@Override
			protected Void doInBackground(Void... params) {
				list_all.clear();
				ArrayList<OfficialOrderList> list=db_myorder.onReadDB(context, num_all);
				if(list!=null){
					list_all.addAll(list);	
				}
				return null;
			}

			protected void onPostExecute(Void result) {
				notifyDataSetChanged(mMyListView_AllOrder,
						mMyOrderAdapter_allOrder, list_all.size(), num_all);
				if (isFirst_all) {
					isFirst_all = false;
					if (loaddialog != null && !loaddialog.isShowing()) {
						loaddialog.show();
					}
					refreshAllOrder(false);
				} else {
					if (loaddialog != null) {
						loaddialog.onDismiss();
					}
				}
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	/**
	 * 写入进行中的订单数据
	 */
	private void onWriteDB_ing(ArrayList<OfficialOrderList> list,boolean isDelete) {
		isWriteIngFinish = false;
		db_myordering.onWriteDB_ing(this, list, isDelete,mHandler);
	}

	/**
	 * 写入全部订单数据
	 */
	private void onWriteDB(ArrayList<OfficialOrderList> list, boolean isDelete) {
		isWriteFinish = false;
		db_myorder.onWriteDB(this, list, isDelete, mHandler);
	}

	/**
	 * 删除进行中的所有数据
	 */
	public void onDeleteDB_ing() {
		db_myordering.onDelete();
		// db_locations.onDelete();
	}

	/**
	 * 删除全部所有数据
	 */
	public void onDeleteDB() {
		db_myorder.onDelete();
		// db_locations.onDelete();
	}

	@Override
	protected void onActivityResult(final int requestCode, int resultCode,
			Intent data) {
		if (requestCode == this.requestCode) {
			if (list_all.size() > 0) {
				mMyOrderAdapter_allOrder.notifyDataSetChanged();
				mMyListView_AllOrder.setSelection(0);
			}
			if (requestCode == this.requestCode) {
				new Handler().postDelayed(new Runnable() {

					@Override
					public void run() {
						isFirst_all=true;
						refreshAllOrder(true);
					}
				}, 300);

			}

		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	protected void onDestroy() {
		if (mDeleteOrderTask != null
				&& mDeleteOrderTask.getStatus() != AsyncTask.Status.FINISHED)
			mDeleteOrderTask.cancel(true);
		super.onDestroy();

	}

	public void notifyDataSetChanged(final MyListView mMyListView,
			final BaseAdapter adapter, int size, int num) {
		onisShowNodata(adapter);
		if (size >= num) {
			mMyListView.setHasMoreData(true);
		} else {
			mMyListView.setHasMoreData(false);
		}
		adapter.notifyDataSetChanged();
	}

	/**
	 * 只用于删除
	 */
	public void notifyDataSetChanged(final MyListView mMyListView,
			final BaseAdapter adapter) {
		adapter.notifyDataSetChanged();
		onisShowNodata(adapter);

	}

	public void onisShowNodata(BaseAdapter adapter) {
		// if (adapter.getCount() == 0) {
		// if (adapter == mMyOrderAdapter_allOrder) {
		// layout_nodata_all.setVisibility(View.VISIBLE);
		// } else {
		// layout_nodata_ing.setVisibility(View.VISIBLE);
		// }
		//
		// } else {
		// if (adapter == mMyOrderAdapter_allOrder) {
		// layout_nodata_all.setVisibility(View.GONE);
		// } else {
		// layout_nodata_ing.setVisibility(View.GONE);
		// }
		// }
	}
    public void onSearchId(int type,Msgs.Data msgs_data){
    	try{
    		//判断是否读取数据库
    		boolean isRead=true;
    		String order_id=msgs_data.getOrder_id();
        	int order_status=msgs_data.getOrder_status();
        	for(int i=0;i<list_all.size();i++){
        		if(list_all.get(i).getOrder_id().equals(order_id)){
        			list_all.get(i).setOrder_status(order_status+"");
        			if(type==GMsg.OFFICAIL_ONLINE_OFFCAR){
        				list_all.get(i).setOrder_status(Value.ORDER_STATUS_OFFCAR+"");
        			}
        			
        			isRead=false;
        		}
        	}
        	if(isRead){onReadDB(false);}
        	else{
        		notifyDataSetChanged(mMyListView_AllOrder,
						mMyOrderAdapter_allOrder, list_all.size(), num_all);
        	}
    	}catch(Exception e){}
    	
    }
	@Override
	public void onNotify(int type, JSONObject jb, Msgs.Data msgs_data) {
		/** 是否继续执行父类 */
		boolean isContinue = true;
		switch (type) {
		case GMsg.OFFICAIL_ONLINE_PAIDAN:
		case GMsg.OFFICAIL_ONLINE_CANCEL:
		case GMsg.ONLINE_KF_CANCEL:
		case GMsg.OFFICAIL_ONLINE_GAIPAI:
		case GMsg.ONLINE_KF_GAIPAIL:
		case GMsg.OFFICAIL_ONLINE_ONCAR:
		case GMsg.ONLINE_FINISH:
		case GMsg.OFFICAIL_ONLINE_FINISH:
		case GMsg.ONLINE_UNPROCESSED_RESULT:
			isContinue=false;
			isFirst_all = true;
			isFirst_ing = true;
			onSearchId(type,msgs_data);
			super.onNotify(type, jb, msgs_data);
			break;
		case GMsg.OFFICAIL_ONLINE_OFFCAR:
			isContinue=false;
			isFirst_all = true;
			isFirst_ing = true;
			onReadDB(false);

			if (msgs_data != null) {
				final String order_id = msgs_data.getOrder_id();
				MyOrderingDB db_myordering = new MyOrderingDB(context);// 我的进行中的订单数据库
				OfficialOrderList mOfficialOrderList = db_myordering
						.onReadDB_ing(context, order_id);
				String start_city = ToCity.getCity(mOfficialOrderList
						.getOrderDetail().getStart().getAddress());
				String end_city = ToCity.getCity(mOfficialOrderList
						.getOrderDetail().getEnd().getAddress());
				final MyPayOrderDailog payorder_dialog = new MyPayOrderDailog(
						context);
				payorder_dialog.setOrderId(order_id);
				payorder_dialog.setMoney(FormatUtil
						.onFormatPrice(Integer.parseInt(mOfficialOrderList.getPrice())));
				payorder_dialog.setContent(String.format(
						getString(R.string.order),
						DateFormat.onDateRemove_ss(mOfficialOrderList
								.getAppoint_time())
								+ "\n"
								+ start_city
								+ "到"
								+ end_city));
				if (payorder_dialog != null && !payorder_dialog.isShowing()) {
					payorder_dialog.show();
				}
				payorder_dialog.setOnClickPayListener(new onClickPayListener() {
					@Override
					public void onClickPay() {
						Intent intent = new Intent(context,
								OrderEvaluationActivity2.class);
						intent.putExtra(OrderMsg.order_id_finish, order_id);
						intent.putExtra(OrderMsg.finish_type,
								OrderMsg.finish_ing);
						context.startActivityForResult(intent, requestCode);
					}
				});
			}
			break;
		case GMsg.ONLINE_BUSY:
			isContinue=false;
			String text = null;
			try {
				JSONObject json_jmsg = jb.getJSONObject(GMsg.msg_jmsg);
				JSONObject jmsg_data = new JSONObject(
						json_jmsg.getString(GMsg.msg_data));
				msgs_data = (Msgs.Data) new JsonBuild().getData(
						Msgs.Data.class, jmsg_data.toString());
			} catch (JSONException e1) {
			}
			if (msgs_data != null && msgs_data.getText() != null) {
				MyOrderingDB db_myordering = new MyOrderingDB(context);// 我的进行中的订单数据库
				OfficialOrderList mOfficialOrderList = db_myordering
						.onReadDB_ing(context, msgs_data.getOrder_id());
				String start_city = ToCity.getCity(mOfficialOrderList
						.getOrderDetail().getStart().getAddress());
				String end_city = ToCity.getCity(mOfficialOrderList
						.getOrderDetail().getEnd().getAddress());
				MyBusyDailog busyDailog = new MyBusyDailog(this);
				busyDailog.setTitle(msgs_data.getText());
				busyDailog.setContent(DateFormat
						.onDateRemove_ss(mOfficialOrderList.getAppoint_time())
						+ "\n" + start_city + "→" + end_city);
				if (busyDailog != null && !busyDailog.isShowing()) {
					busyDailog.show();
				}
			}

			break;
		case GMsg.ONLINE_BG_ORDER:
			isContinue=false;
			isFirst_all = true;
			isFirst_ing = true;
			onReadDB(false);

			break;
		case GMsg.ONLINE_RELOGIN:
			isContinue=false;
			stopService(new Intent(this, LoginService.class));
			MyAlertDailog dialog = new MyAlertDailog(this);
			Resources res = context.getResources();
			dialog.setTitle(res.getString(R.string.mydailog_title));
			dialog.setContent(res.getString(R.string.mydailog_content_login));
			dialog.setLeftButtonText(res.getString(R.string.mydailog_exit));
			dialog.setRightButtonText(res.getString(R.string.mydailog_relogin));
			if (dialog != null && !dialog.isShowing()) {
				dialog.show();
			}
			dialog.setOnClickLeftListener(new onClickLeftListener() {
				@Override
				public void onClickLeft() {
					stopService(new Intent(context, LoginService.class));
					DataCleanManager.cleanDatabases(context);
					DataCleanManager.cleanSharedPreference(context);
					Intent intent = new Intent(context, MainActivity.class);
					intent.putExtra(MainMsg.extra_quit, MainMsg.INTENT_QUIT);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					overridePendingTransition(0, 0);
					finish();
					overridePendingTransition(0, 0);
				}
			});
			dialog.setOnClickRightListener(new onClickRightListener() {

				@Override
				public void onClickRight() {
					Intent intent = new Intent();
					intent.setClass(context, LoginActivity.class);
					startActivity(intent);
				}
			});
			break;
		case GMsg.ONLINE_KF_CHANGE:
			isContinue=false;
			ToastUtil.showToast(context, R.string.toast_change);
			isFirst_all = true;
			isFirst_ing = true;
			onReadDB(false);
			break;
		}
		if (isContinue) {
			super.onNotify(type, jb, msgs_data);
		}
	}

	@Override
	public void onOrderFinish(int status,int flag,int own_expense, ArrayList<OfficialOrderList> list) {
		if (loaddialog != null) {
			loaddialog.dismiss();
		}
		int num=num_all;
		if(flag==Value.TYPE_ING){
			num=num_ing;
		}
		switch(status){
		case MyUnprocessedTask.STATUS_SUCCESS:
			if(start_id.equals(MyOrderTask.TYPE_REFRESH)){//刷新
				list_all.clear();
				  if (list != null) {
					  list_all.addAll(list);
					  pullToRefreshLayout_all.refreshFinish(PullToRefreshLayout.SUCCEED);
						notifyDataSetChanged(mMyListView_AllOrder, mMyOrderAdapter_allOrder,
								list_all.size(), num);
//						onWriteDB(list_all, true);
//						if(flag ==Value.TYPE_ING){
//							onWriteDB_ing(list,true);
//						}
				
					}
			  }else{//加载
				  if (list != null&&!list.isEmpty()) {
					  list_all.addAll(list);
//						onWriteDB(list_all, false);
//						if(flag ==Value.TYPE_ING){
//							onWriteDB_ing(list,false);
//						}
						notifyDataSetChanged(mMyListView_AllOrder, mMyOrderAdapter_allOrder,
								list.size(), num);
				  }else{
					  mMyListView_AllOrder.setHasMoreData(false);
						ToastUtil.showToast(context,
								getString(R.string.in_the_end));
				  }
			  }
			break;
		  case MyUnprocessedTask.STATUS_FAil:
			  ToastUtil.showToast(context,
						getString(R.string.no_network));
			  if(start_id.equals(MyOrderTask.TYPE_REFRESH)){//刷新
				  list_all.clear();
				  pullToRefreshLayout_all.refreshFinish(PullToRefreshLayout.FAIL);
					notifyDataSetChanged(mMyListView_AllOrder, mMyOrderAdapter_allOrder,
							list_all.size(), num);
//					onWriteDB(list_all, true);
//					if(flag ==Value.TYPE_ING){
//						onWriteDB_ing(list,true);
//					}
			  }else{
				  mMyListView_AllOrder.setHasMoreData(false);
				 ToastUtil.showToast(context,
							getString(R.string.in_the_end));
			  }
			  break;
		  case MyUnprocessedTask.STATUS_NULL:
			  if(start_id.equals(MyOrderTask.TYPE_REFRESH)){//刷新
				  list_all.clear();
				  pullToRefreshLayout_all.refreshFinish(PullToRefreshLayout.SUCCEED);
					notifyDataSetChanged(mMyListView_AllOrder, mMyOrderAdapter_allOrder,
							list_all.size(), num);
//					onWriteDB(list_all, true);
//					if(flag ==Value.TYPE_ING){
//						onWriteDB_ing(list,true);
//					}
			  }else{
				  mMyListView_AllOrder.setHasMoreData(false);
				 ToastUtil.showToast(context,
							getString(R.string.in_the_end));
			  }
			 
			  break;
		}
	}

	/** 由于中途取消加载，马上点击Touch事件的话会出发下啦导致奔溃，所以500毫秒内，不能点击 */
	public boolean isTouch = true;

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if (!isTouch) {
			return true;
		}
		return super.dispatchTouchEvent(ev);
	}

	@Override
	public void onDismiss(DialogInterface dialog) {
		isTouch = false;
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				isTouch = true;
			}
		}, 500);
		if (mDeleteOrderTask != null
				&& mDeleteOrderTask.getStatus() != AsyncTask.Status.FINISHED)
			mDeleteOrderTask.cancel(true);
		super.onDismiss(dialog);
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		
		
	}

	@Override
	public void onPageSelected(int arg0) {
		mViewPager.setCurrentView(mMyPagerAdapter.getView(arg0));
		viewpageId = arg0;
		Animation animation = null;
		switch (arg0) {
		case 0:
			if(oldviewpageId==2){
				animation = AnimationUtils.loadAnimation(this,
						R.anim.viewpagebar_2_to_0);
			}else if(oldviewpageId==1){
				animation = AnimationUtils.loadAnimation(this,
						R.anim.viewpagebar_1_to_0);
			}
			
			tv_all.setTextColor(getResources().getColor(R.color.btn_nor));
			tv_gongwu.setTextColor(getResources().getColor(R.color.text_nor));
			tv_putong.setTextColor(getResources().getColor(R.color.text_nor));
			break;
		case 1:
            if(oldviewpageId==0){
            	animation = AnimationUtils.loadAnimation(this,
						R.anim.viewpagebar_0_to_1);
			}else if(oldviewpageId==2){
				animation = AnimationUtils.loadAnimation(this,
						R.anim.viewpagebar_2_to_1);
			}
			tv_all.setTextColor(getResources().getColor(R.color.text_nor));
			tv_gongwu.setTextColor(getResources().getColor(R.color.btn_nor));
			tv_putong.setTextColor(getResources().getColor(R.color.text_nor));
			break;
		case 2:
            if(oldviewpageId==0){
            	animation = AnimationUtils.loadAnimation(this,
						R.anim.viewpagebar_0_to_2);
			}else if(oldviewpageId==1){
				animation = AnimationUtils.loadAnimation(this,
						R.anim.viewpagebar_1_to_2);
			}
			tv_all.setTextColor(getResources().getColor(R.color.text_nor));
			tv_gongwu.setTextColor(getResources().getColor(R.color.text_nor));
			tv_putong.setTextColor(getResources().getColor(R.color.btn_nor));
			break;

		}
		if(animation!=null){
		animation.setFillAfter(true);// True:图片停在动画结束位置
		animation.setDuration(300);
		image_bar.startAnimation(animation);
		}
		oldviewpageId=arg0;
		
	}
}
